import React, { useEffect, useState } from "react";
import { useModel } from "@umijs/max";
import { modalPropsType } from "@/constants/types";
import { Modal, Form, Input, Radio, Row, Col, Cascader, Space, Upload, Button, InputNumber } from "antd";
import XlSelect from "@/components/Form/XlSelect";
import { useComponentDidMount } from "@/hooks";
import { PlusOutlined } from "@ant-design/icons";
import type { RcFile, UploadProps } from 'antd/es/upload';
import type { UploadFile } from 'antd/es/upload/interface';
import { fetchInnerUserSalesOptions, fileUpload } from "@/services/common";
import { fetchCompanyDetail } from "../../services";
import { isEmptyObj, userIsSales } from "@/utils/util";
import  { isMonthSettlement, isTicketSettlement, companyIsPersonal } from "@/utils/dictUtil";
import { useRequest } from "ahooks";
import { getStorage } from "@/utils/storage";

const {Item} = Form;
const rules = [{required: true, message: '此项必填'}];
const labelCol = {span: 4}

const CompanyUpdate = ({title, loading, onCancel, onSubmit, visible, currentRow = {}}: modalPropsType) => {
  const [form] = Form.useForm();
  const { getDict } = useModel('dictModel');
  const { areaData, fetchAreaData } = useModel('areaModel');
  const userInfo = getStorage('userInfo');

  const {data: sales} = useRequest(fetchInnerUserSalesOptions);


  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  // const [detail, setDetail] = useState({});

  // 获取详情
  const fetchDetail = async (id: string) => {
    const res = await fetchCompanyDetail({id});
    if (!isEmptyObj(res)) {
      const list = res?.attachments?.length > 0 ? res?.attachments?.map((v: any) => ({
        ...v,
        uid: v?.path,
        isDefault: true,
        status: 'done',
      })) : [];
      const rowData = {
        ...res,
        identificationPath: list,
        areaAddress: [res?.province, res?.city, res?.area].filter(v => !!v),
        settlementMethod: companyIsPersonal(res?.type) ? '2' : res?.settlementMethod,
        payNode: isTicketSettlement(res?.settlementMethod) ? res?.payNode : undefined,
        payMonth: isMonthSettlement(res?.settlementMethod) ? res?.payMonth : undefined,
        payDay: isMonthSettlement(res?.settlementMethod) ? res?.payDay : undefined
      }
      if (res?.attachments?.length > 0) {
        setFileList(res?.attachments?.map((v: any) => ({
          ...v,
          uid: v?.path,
          isDefault: true,
          status: 'done',
        })));
      }
      form.setFieldsValue(rowData);
      // setDetail(rowData);
    }
  }

  const getUrlAndName = (fileObj: any) => {
    if (isEmptyObj(fileObj)) {
      return {
        identificationPath: undefined,
        identificationFileName: undefined,
      }
    }
    if (fileObj?.isDefault) {
      // todo 
      return {
        identificationPath: fileObj?.path,
        identificationFileName: fileObj?.name,
      }
    }
    return {
      identificationPath: fileObj?.response,
      identificationFileName: fileObj?.response?.split('/')?.[1],
    }
  }
  const handleSubmit = async () => {
    const res = await form.validateFields();
    onSubmit({
      ...res,
      province: res?.areaAddress?.[0],
      city: res?.areaAddress?.[1],
      area: res?.areaAddress?.[2],
      areaAddress: undefined,
      ...getUrlAndName( res?.identificationPath?.[0]),
      id: currentRow?.id
    });
  }

  // 企业类型
  const customType = getDict('customType');
  // 客户属性
  const customerAttr = getDict('customerAttr');
  // 结算方式
  const settlement = getDict('settlement');
  // 付款时间
  const payTime = getDict('payTime');
  // 付款节点
  const payNode = getDict('payNode');

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };

  const getBase64 = (file: RcFile): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as RcFile);
    }

    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
    setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
  };

  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    setFileList(newFileList);
  };
  const handleRemove = (file: any) => {
    const fileIndex = fileList.findIndex(v => v.uid === file.uid);
    if (fileIndex >= 0) {
      const arr = [...fileList];
      arr.splice(fileIndex, 1);
      setFileList(arr);
      form.setFieldsValue({
        identificationPath: arr
      });
    } else {
      form.setFieldsValue({identificationPath: []});
    }
  }
  const handleCancel = () => setPreviewOpen(false);


  const uploadFileReq = ({file, filename, onSuccess, onError, data = {}}: any) => {
    const formData = new FormData();
    formData.append(filename, file);
    Object.keys(data).forEach(key => {
      formData.append(key, data?.[key]);
    })
    fileUpload(formData).then(
      res => {
        if (res?.code === '0') {
          onSuccess(res?.data);
        } else {
          onError(res?.data)
        }
      }
    )
  }

  const handleTypeChange = (e: any) => {
    form.setFieldsValue({
      nickName: '',
      fullName: '',
      identification: '',
      identificationPath: undefined,
      settlementMethod: e.target.value === '2' ? '2' : undefined
    });
    setFileList([]);
  }
  const handleSaleChange = (saleId: any) => {
    if (saleId) {
      const realName = sales.find((v: any) => v.id === saleId)?.realName;
      form.setFieldValue('salesName', realName);
    } else {
      form.setFieldValue('salesName', undefined);
    }
  }


  useEffect(() => {
    if (currentRow?.id) {
      fetchDetail(currentRow?.id);
    }
  }, [currentRow?.id])

  useComponentDidMount(() => {
    fetchAreaData();
  })
  return (
    <>
      <Modal
        open={visible}
        confirmLoading={loading}
        title={title}
        width="700px"
        maskClosable={false}
        onCancel={onCancel}
        onOk={handleSubmit}
      >
      <Form form={form} labelCol={labelCol} className="modal-form-padding">
          <Item name="type" label="客户类型" rules={rules}>
            <Radio.Group onChange={handleTypeChange} options={customType} />
          </Item>
          <Row>
            <Col span={12}>
              <Item name="category" labelCol={{span: 8}} label="客户属性" rules={rules}>
                <Radio.Group options={customerAttr} />
              </Item>
            </Col>
            {
              !userIsSales(userInfo) && (
                <Col span={12}>
                  <Item name="salesId" labelCol={{span: 8}} label="所属销售" rules={rules}>
                    <XlSelect onChange={handleSaleChange} showSearch optionFilterProp="label" dataLabel="realName" dataValue="id" options={sales || []} />
                  </Item>
                  <Item name="salesName" noStyle hidden>
                    <Input />
                  </Item>
                </Col>
              )
            }
          </Row>
          <Item noStyle shouldUpdate={(prev, next) => prev?.type !== next?.type}>
            {({getFieldValue}) => {
              const type = getFieldValue('type');
              const isPersonal = companyIsPersonal(type);
              
              return isPersonal ? (
                <Item name="nickName" label="姓名" rules={rules}>
                  <Input />
                </Item>
              ) : (
                <>
                  <Item name="nickName" label="公司简称" rules={rules}>
                    <Input placeholder="城市加公司简称，例如:深圳星联全球" />
                  </Item>
                  <Item name="fullName" label="公司全称" rules={rules}>
                    <Input />
                  </Item>
                </>
              )
            }}
          </Item>
          <Row gutter={20}>
            <Col span={12}>
              <Item labelCol={{span: 8}} name="contacts" label="联系人" rules={rules}>
                <Input />
              </Item>
            </Col>
            <Col span={12}>
              <Item labelCol={{span: 4}} name="mobile" label="电话" rules={rules}>
                <Input />
              </Item>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={12}>
              <Item name="areaAddress" labelCol={{span: 8}} label="地址">
                <Cascader showSearch fieldNames={{label: 'name', value: 'name', children: 'children'}} options={areaData} />
              </Item>
            </Col>
            <Col span={12}>
              <Item name="address">
                <Input />
              </Item>
            </Col>
          </Row>
          <Item noStyle shouldUpdate={(prev, next) => prev?.type !== next?.type}>
            {({getFieldValue}) => {
              const type = getFieldValue('type');
              const picTitle = companyIsPersonal(type) ? '身份证照片' : '营业执照';
              const picIdTitle = companyIsPersonal(type) ? '身份证号码' : '统一信用代码';
              const maxCount = companyIsPersonal(type) ? 2 : 1;

              return (
                <>
                  <Item label={picTitle} name="identificationPath" valuePropName="fileList" getValueFromEvent={normFile}>
                    <Upload 
                      maxCount={maxCount} 
                      customRequest={uploadFileReq}
                      onPreview={handlePreview}
                      onChange={handleChange}
                      onRemove={handleRemove}
                      // beforeUpload={() => false}
                      fileList={fileList}
                      data={{businessCode: 'identification_code'}} 
                      listType="picture-card">
                      {fileList.length >= maxCount ? null : (
                        <div>
                          <PlusOutlined />
                          <div style={{ marginTop: 8 }}>上传</div>
                        </div>
                      )}
                    </Upload>
                  </Item>
                  <Item name="identification" label={picIdTitle}>
                    <Input />
                  </Item>
                </>
              );
            }}  
          </Item>
          <Row gutter={20}>
            <Col span={10}>
              <Item noStyle shouldUpdate={(prev, next) => prev.settlementMethod !== next.settlementMethod}>
                {({getFieldValue}) => {
                  const type = getFieldValue('type');
                  return (
                    <Item name="settlementMethod" labelCol={{span: 10}} label="结算方式" rules={rules}>
                      <XlSelect 
                        disabled={String(type) === '2'} 
                        onChange={() => form.setFieldsValue({payNode: undefined, payMonth: undefined, payDay: undefined})}
                        options={settlement}
                      />
                    </Item>
                  )
                }}
              </Item>
            </Col>
            <Col span={14}>
              <Item noStyle shouldUpdate={(prev, next) => prev.settlementMethod !== next.settlementMethod}>
                {({getFieldValue}) => {
                  const settlement = getFieldValue('settlementMethod');
                  if (String(settlement) === '1') {
                    return (
                      <Item label="付款时间" required labelCol={{span: 5}}>
                        <Space>
                          <Item name="payMonth" rules={rules} noStyle>
                            <XlSelect options={payTime} style={{width: '150px'}} optins={[]} />
                          </Item>
                          <Item name="payDay" rules={rules} noStyle>
                            <InputNumber min={1} max={31} />
                          </Item>
                        </Space>
                      </Item>
                    );
                  }
                  return (
                    <Item label="付款节点" name="payNode" rules={rules} labelCol={{span: 5}}>
                       <XlSelect options={payNode} style={{width: '290px'}} optins={[]} />
                    </Item>
                  );
                }}
              </Item>
            </Col>
          </Row>
          {/* <Item label="上传合同" name="identificationFileName" valuePropName="fileList" getValueFromEvent={normFile} rules={rules}>
            <Upload maxCount={1}  customRequest={uploadFileReq} data={{businessCode: 'contracts'}}>
              <Button style={{width: 200, height: 30}} icon={<UploadOutlined />}>点击上传</Button>
            </Upload>
          </Item> */}
        </Form> 
      </Modal>
      <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
        <img alt="example" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </>
  );
}
export default CompanyUpdate;